
import time
from applications.extensions import db
from flask import Blueprint, request
from applications.models import LicenceInfo


licenceInfo_bp = Blueprint('licenceInfo', __name__, url_prefix='/licenceInfo')

@licenceInfo_bp.get('/getAlllicenceInfo')
# @login_required
def getAlllicenceInfo():
    try:
        user_phonenum = request.args.get("user_phonenum")
        if len(db.session.query(LicenceInfo).filter(LicenceInfo.phonenum == user_phonenum).all()) == 0:
            licence_infotmp = LicenceInfo(phonenum=user_phonenum, status="正常")
            db.session.add(licence_infotmp)
            db.session.commit()
            licence_infotmp = LicenceInfo.query.filter_by(phonenum=user_phonenum).first()
            return {"code": 200, "message": "success",
                        "data": {"licence_id": licence_infotmp.licence_id, "reg_time": licence_infotmp.reg_time, "out_time": licence_infotmp.out_time,
                                 "status":licence_infotmp.status}}
        else :
            licence_infotmp = LicenceInfo.query.filter_by(phonenum=user_phonenum).first()
            return {"code": 200, "message": "success",
                        "data": {"licence_id": licence_infotmp.licence_id, "reg_time": licence_infotmp.reg_time, "out_time": licence_infotmp.out_time,
                                 "status":licence_infotmp.status}}
    except BaseException as e:
        print(e)
        return "success"


@licenceInfo_bp.post('/setLicenceStatus')
# @login_required
def setLicenceStatus():
    try:
        data = request.form
        status = data.get("status")
        user_phonenum = data.get("user_phonenum")
        licence_infotmp = LicenceInfo.query.filter_by(phonenum=user_phonenum).first()
        if(status == "注销"):
            db.session.delete(licence_infotmp)
            db.session.commit()
        else:
            licence_infotmp.status=status
            db.session.commit()
            return {"code": 200, "message": "success"}
    except BaseException as e:
        print(e)
        return {"code": 200, "message": "fail"}
@licenceInfo_bp.post('/newlicence')
def newlicence():
    try:
        data = request.form
        phonenum = data.get("user_phonenum")
        status = "正常"
        licence_infotmp = LicenceInfo.query.filter_by(phonenum=phonenum).first()
        if licence_infotmp:
            return {"code":200,"message":"noneed"}
        else:
            licence = LicenceInfo(phonenum=phonenum, status=status)
            db.session.add(licence)
            db.session.commit()
            return {"code":200,"message":"success"}
    except BaseException as e:
        print(e)
        return {"code":200,"message":"fail"}